<template>
  <div>
    <el-form class="row mb-1" :inline="true" :model="ruleForm">
      <div class="col-xs-12 col-sm-6 col-lg-4 col-xxl-3">
        <el-form-item label="">
          <el-input placeholder="请输入用户名、ID、手机号" @change="start" v-model="like">
          </el-input>
        </el-form-item>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-4 col-xxl-3">
        <el-form-item label="">
          <el-select clearable v-model="formquery._include.teamid" placeholder="团队" style="width: 150px" :remote-method="(query: string) =>
            $store.dispatch('actionteam', { _like: ['name', query] })
            " filterable remote>
            <el-option v-for="(k, i) in getteam" :key="i" :label="k.name" :value="Number(k.ID)"></el-option>
          </el-select>
        </el-form-item>
      </div>


      <div class="col-xs-12 col-sm-6 col-lg-4 col-xxl-3">
        <el-form-item label="创建时间">
          <el-date-picker v-model="createdAt" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
            :shortcuts="shortcuts"></el-date-picker>
        </el-form-item>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-4 col-xxl-3">
        <el-form-item label="登录时间">
          <el-date-picker v-model="lasttime" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
            :shortcuts="shortcuts"></el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <div class="row  mb-1">
      <div class="col">
        <el-button @click="start" type="primary">查询</el-button>
        <el-button @click="dialogVisible = true" type="primary">+ 添加用户</el-button>
        <el-button @click="drawer = true" type="primary">+ 批量添加</el-button>
      </div>
    </div>
    <div v-if="selectarr" v-show="handleSelectionChange" class="row selecttable  mb-1">
      <div>
        <el-tag :key="v.ID" v-for="(v, i) in selectarr" closable :disable-transitions="false" @close="handleClose(i)">{{
          v.name ? v.name : v.ID
        }}</el-tag>
      </div>
    </div>
    <div class="row  mb-1">
      <div class="col">
        <el-table ref="multipleTable" border :data="tableData" height="65vh" style="width: 100%" @sort-change="sortchange"
          @cell-click="userhandleCurrentChange ? () => { } : handleClick" @selection-change="(d) => handleChange(d)"
          :highlight-current-row="!!userhandleCurrentChange" @current-change="userCurrentChange">
          <el-table-column v-if="handleSelectionChange" type="selection" width="55"></el-table-column>

          <el-table-column v-for="v in tableattr" :key="v.prop" :prop="v.prop" :label="v.label" :formatter="v.formatter"
            :sortable="v.sortable"></el-table-column>
          <el-table-column prop="name" label="答题正确率">
            <template #default="scope">
              {{
                scope.row.userquestionaccount ? Math.floor(scope.row.userquestionaccount / scope.row.userquestioncount *
                  100)
                :
                0
              }}
            </template>

          </el-table-column>
          <el-table-column prop="userquestioncount" label="答题次数">
          </el-table-column>

          <el-table-column prop="remarks"
            :formatter="({ teamuser = [] }) => teamuser.map((e: any) => e.team.name).join('，')" label="所在团队">
            <template #default="{ row }">
              {{ row.teamuser.map((e: any) => e.team.name).join(',') }}
              {{ row.team.map((e: any) => e.name).join(',') }}
            </template>
          </el-table-column>

          <el-table-column prop="remarks" label="备注"></el-table-column>
          <el-table-column prop="remarks" label="操作">
            <template #default="scope">
              <el-button type="warning" @click="
                change(scope.row)
                ">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="row  mb-1">
      <div class="col">
        <el-pagination @current-change="handleCurrentChange" :page-size="formquery._limit"
          :page-sizes="[20, 50, 100, 200, 300, 400, count]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="(e) => formquery._limit = e" :total="count"></el-pagination>
      </div>
    </div>

    <el-dialog :title="title" v-model="dialogVisible" width="650">
      <el-form :model="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="ruleForm.phonenum"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ruleForm.remarks"></el-input>
        </el-form-item>
        <div class="row">
          <div class="col text-right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <el-drawer id="user1" modal-class="user1" size="1200px" append-to-body v-model="drawer" title="批量添加">
      <Addtable v-bind="{ close }" />
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { difference } from "underscore";
import { toLocaleDateString } from "../../../util/time";
import {
  asyncadmincreateorupdateuser,
  asyncadmingetuser,
  Iobj,
} from "../../../api/index";
import { User } from "../data";
import study from "../../../mysql_interface/studycodemodel";
import { modelFind } from "../../../util/modelkey";
import { Storekey, TtableU } from "../../../interface";
import { debounce } from "underscore";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import Addtable from "./addtable.vue";
import moment from "moment";
import { getExceltodownload } from "../../../util/excel";
import { useStore } from "vuex";
import { assign } from 'lodash-es';

const prop = defineProps<{ tablekey?: Array<keyof study.Iuser>, handleSelectionChange?: (n: study.Iuser[]) => void, selectarr?: study.Iuser[], userhandleCurrentChange?: (n: study.Iuser) => void }>()
const like = ref()
const formquery = reactive<Iobj<study.Iuser>>({
  _limit: 20,
  _offset: 0,
  _order: 'ID',
  _include: {},
})
const title = ref('添加')

const dialogVisible = ref(false)

const ruleForm = ref<study.Iuser>(assign({ password: '000000' }, User))

const porparr = ref<Studycodemodel.Iuser[]>([])


const createdAt = ref([])
const lasttime = ref([])
const builddate = ref<Array<any[]>>([])
const drawer = ref(false)
const close = ref(false)


const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "本周",
    value: () => {
      const end = new Date();

      const start = moment().day(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = moment().date(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = moment().date(-90).unix() * 1000;
      return [start, end];
    },
  },
]

const store = useStore(Storekey)

const tableData = computed(() => {
  return store.state.users?.rows || []
})

const count = computed(() => {
  return store.state.users?.count || 0
})

const getteam = computed(() => {
  return store.state.team?.rows || []
})

watch(formquery, () => {
  start()
})

const multipleTable = ref()

watch(() => prop.selectarr, () => {
  porparr.value = []
  for (const v of tableData.value) {
    const d = prop.selectarr?.find(e => e.ID === v.ID)
    if (d) {
      porparr.value.push(d)
      multipleTable.value?.toggleRowSelection(v, true)
    } else {
      multipleTable.value?.toggleRowSelection(v, false)
    }
  }
})



watch(() => drawer.value, (v) => {
  close.value = v
})

async function start() {
  const {
    _limit,
    _offset,
    _order,
    _sortable,
    _include = {}
  } = formquery;
  porparr.value = []
  try {
    const t: Iobj<Studycodemodel.Iuser> = {
      _limit: _limit,
      _offset: _offset,
      _order: _order,
      _sortable: _sortable,
      _include: {}
    };
    if (like.value) {
      t._like = [
        ['ID', like.value],
        ['name', like.value],
        ['remarks', like.value],
        ['phonenum', like.value],
        ['gid', like.value],
      ]
    }
    if (!_order) {
      delete t._sortable;
      delete t._order;
    }
    if (createdAt.value && createdAt.value.length) {
      t.createdAt = {
        lt: createdAt.value[1],
        gt: createdAt.value[0],
      };
    }
    if (lasttime.value && lasttime.value.length) {
      t.lasttime = {
        lt: lasttime.value[1],
        gt: lasttime.value[0],
      };
    }
    if (_include && _include.teamid && t._include) {
      t._include.teamuser = ['teamid', _include.teamid]
    }
    await store.dispatch("actionusers", t);

  } catch (e: any) {
    ElMessage.error(e);
  }
}

function handleCurrentChange(val: number) {
  formquery._offset = Number(formquery._limit) * (val - 1);
}


async function change(row: Studycodemodel.Iuser) {
  ruleForm.value = await asyncadmingetuser(row)
  dialogVisible.value = true
}

function handleClick(row: Studycodemodel.Iuser) { }

function sortchange(row: { prop: any; order: any }) {
  const { prop, order } = row;
  if (order == "descending") {
    formquery._sortable = "DESC";
  } else {
    formquery._sortable = "ASC";
  }
  formquery._order = prop;
  start();
}

const formatter = (data: Studycodemodel.Iuser) => toLocaleDateString(data.updatedAt)


function _handleChange(data: study.Iuser[]) {
  if (prop.handleSelectionChange) {
    // 查找要添加的
    const datanum = data.map((v) => v.ID);
    const _porparr = porparr.value.map((v) => v.ID);
    const add = difference(datanum, _porparr);
    // 查找要删除的
    const out = difference(_porparr, datanum);
    const _data = prop.selectarr?.map((v) => v) || [];
    for (let v of add) {
      const e = tableData.value.find(({ ID }) => ID === v);
      if (e) {
        _data.push(e);
      }
    }

    for (let v of out) {
      const index = _data.findIndex(({ ID }) => v === ID);
      _data.splice(index, 1);
    }
    if (out.length || add.length) {
      prop.handleSelectionChange(_data);
    }
  }
}

function userCurrentChange(data: study.Iuser) {
  if (prop.userhandleCurrentChange) prop.userhandleCurrentChange(data);
}

async function submit() {
  try {
    await asyncadmincreateorupdateuser(ruleForm.value);
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    start();
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage({
      message: e,
      type: "error",
    });
  }
}

function handleClose(v: number) {
  const data: study.Iuser[] = [];

  if (prop.handleSelectionChange && prop.selectarr) {
    prop.selectarr.forEach((vo, i) => {
      if (i !== v) {
        data.push(vo);
      }
    });
    prop.handleSelectionChange(data);
  }
}

function api_import_user(e: {
  error: number;
  data: {
    importuser: Studycodemodel.Iuser[];
    user: Studycodemodel.Iuser[];
    _erru: Studycodemodel.Iuser[];
  };
  msg: string;
}) {
  if (e.error) {
    builddate.value.push([e.msg]);
    ElMessage.error(e.msg);
    start();
  } else {
    builddate.value.push(["注册成功用户"]);
    // builddate.value = builddate.value.concat(
    //   ...e.data.importuser
    //     .filter((_e, k) => k === 0)
    //     .map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.importuser.map((e) => Object.values(e).map(e => String(e)))
    );
    builddate.value.push(["之前添加成功用户"]);
    // builddate.value = builddate.value.concat(
    //   e.data.user.filter((e, k) => k === 0).map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.user.map((e) => Object.values(e).map(e => String(e)))
    );
    builddate.value.push(["之前添加失败用户"]);
    builddate.value = builddate.value.concat(
      e.data._erru.map((e) => Object.values(e).map(e => String(e)))
    );
    getExceltodownload(builddate.value, "注册完成日志");
    ElMessage.success(e.msg);
    builddate.value = [];
    drawer.value = false;
    start();
  }
}

const handleChange = debounce(_handleChange, 300)
const _tableattr: Array<TtableU<study.Iuser>> = [
  { prop: "ID", label: "用户id", sortable: true },
  { prop: "name", label: "用户名称", sortable: true },
  { prop: "xingming", label: "姓名", },
  {
    prop: "createdAt",
    label: "创建时间",
    sortable: true,
    formatter: ({ createdAt }) => formatter({ updatedAt: createdAt }),
  },
  {
    prop: "lasttime",
    label: "上次登录时间",
    sortable: true,
    formatter: ({ lasttime }) => formatter({ updatedAt: lasttime }),
  },
  {
    prop: "userquestiontime",
    label: "最近做题时间",
    formatter: ({ userquestiontime }) => formatter({ updatedAt: userquestiontime }),
  },
];

const tableattr = ref<TtableU<Studycodemodel.Iuser>[]>(modelFind(_tableattr, prop.tablekey))


onMounted(() => {
  store.state.socket.on('api_import_user', api_import_user)
  start()
  const table: any = multipleTable.value;
  for (const v of tableData.value) {
    const d = prop.selectarr?.find((e) => e.ID === v.ID);
    if (d) {
      porparr.value.push(d);
      table.toggleRowSelection(v, true);
    } else {
      table.toggleRowSelection(v, false);
    }
  }
})


</script>

<style scoped>
.selecttable {
  height: 80px;
  overflow: auto;
}
</style>

<style>
.user1 .el-drawer__header {
  margin-bottom: 0;
  padding: 0 20px;
}
</style>